﻿#pragma once
/**
 *　音频采集模块
 */
#include <mutex>
#include <memory>
#include <atomic>
#include "api/scoped_refptr.h"
#include "rtc_base/thread.h"
#include "pc/local_audio_source.h"
#include "api/audio_codecs/builtin_audio_decoder_factory.h"
#include "rtc_base/ref_counted_object.h"


/*

	rtc::scoped_refptr<AudioTrackSourceInput> audioSource;
	m_audioDeviceModule->Terminate();
	audioSource = AudioTrackSourceInput::Create(audiourl, opts);
	return audioSource;


*/
class AudioCapture;

// 音频轨道输入源类
class AudioTrackSourceInput : public webrtc::Notifier<webrtc::AudioSourceInterface> {
public:
	// 创建音频轨道输入源实例
	static rtc::scoped_refptr<AudioTrackSourceInput> Create(const std::string& uri, const std::map<std::string, std::string>& opts) {
		return rtc::scoped_refptr<AudioTrackSourceInput>(new rtc::RefCountedObject<AudioTrackSourceInput>(uri, opts, true));
	}

	// 获取音频源状态
	SourceState state() const override { return kLive; }

	// 判断是否为远程音频源
	bool remote() const override { return true; }

	// 添加音频轨道接收者
	virtual void AddSink(webrtc::AudioTrackSinkInterface* sink) override;

	// 移除音频轨道接收者
	virtual void RemoveSink(webrtc::AudioTrackSinkInterface* sink) override;

	// 发送录制的音频缓冲区
	int32_t SendRecordedBuffer(int8_t* audio_data, uint32_t data_len, int bits_per_sample, int sample_rate, size_t number_of_channels, int64_t sourcets);

protected:
	// 构造函数
	AudioTrackSourceInput(const std::string& uri, const std::map<std::string, std::string>& opts, bool wait);

	// 析构函数
	virtual ~AudioTrackSourceInput();

private:
	AudioCapture* m_pAudioCapture = nullptr; // 音频采集模块指针
	//rtc::scoped_refptr<webrtc::AudioDecoderFactory> m_factory; // 音频解码工厂指针

	std::vector<int16_t> m_vecbuffer; // 音频数据缓冲区

	std::list<webrtc::AudioTrackSinkInterface*> m_sinks; // 音频轨道接收者列表

	std::mutex m_sink_lock; // 互斥锁，用于保护音频轨道接收者列表
	bool m_wait; // 是否等待标志
	int64_t m_previmagets; // 上一帧图像时间戳
	int64_t m_prevts; // 上一帧时间戳
	std::string m_audiourl; // 音频URL
};